package com.huxiu.pagers.qunzu;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.R;
import com.huxiu.WoFaBiaoActivity;
import com.huxiu.base.ZiXunDetailPager;
import com.huxiu.holder.HuaTiHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.HuaTiItem;
import com.huxiu.net.responses.HuaTiListDataResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by ${qcl} on 2015/11/19.
 */
public class HuaTiDetailMine extends ZiXunDetailPager implements View.OnClickListener {

    @ViewInject(R.id.lv_tabdetail_list)
    private RefreshListView lv_tabdetail_list;// 话题列表
    @ViewInject(R.id.wofabiao)
    private LinearLayout wofabiao;
    @ViewInject(R.id.wohuifu)
    private LinearLayout wohuifu;

    @ViewInject(R.id.wofabiao_text)
    private TextView wofabiao_text;

    @ViewInject(R.id.wohuifu_text)
    private TextView wohuifu_text;

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载中
    @ViewInject(R.id.reLoadView)
    private LinearLayout reLoadView;// 加载中
    private Runnable runnable;
    private Handler handler;
    private String noListKey;

    //这里传过来的type：1，代表我的话题 2，代表发现中的话题
    public HuaTiDetailMine(Context context) {
        super(context);

    }

    @Override
    protected View initView() {
        View viewAll = View.inflate(mContext, R.layout.list_mine_huati_detail, null);
        ViewUtils.inject(this, viewAll);
        View top = View.inflate(mContext, R.layout.list_header_qunzu_huati, null);
        ViewUtils.inject(this, top);
        wofabiao.setOnClickListener(this);
        wohuifu.setOnClickListener(this);
        reLoadView.setOnClickListener(this);
        lv_tabdetail_list.addHeaderView(top);

        //在oncreat等中实例化
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                //要做的事情
                reLoadView.setVisibility(View.VISIBLE);
                loading.setVisibility(View.INVISIBLE);
            }
        };
        // 给下拉刷新Listview设置监听器
        lv_tabdetail_list.setOnRefreshingListener(new MyOnRefreshingListener());
        return viewAll;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wofabiao:
                UmenEvent.UmengEventMap(mContext, UmenEvent.GROUP_PAGE_LOGIN, UmenEvent.GROUP_LOGIN_MY_PUBLISH);
                Intent intent = new Intent(mContext, WoFaBiaoActivity.class);
                intent.putExtra("type", "wofabiao");
                mContext.startActivity(intent);
                break;
            case R.id.wohuifu:
                UmenEvent.UmengEventMap(mContext, UmenEvent.GROUP_PAGE_LOGIN, UmenEvent.GROUP_LOGIN_MY_REPLY);
                intent = new Intent(mContext, WoFaBiaoActivity.class);
                intent.putExtra("type", "wohuifu");
                mContext.startActivity(intent);
                break;
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);
                initData();
                break;

        }
    }

    @Override
    public void initData() {
        if (!NetUtil.checkNet(mContext)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.INVISIBLE);
            lv_tabdetail_list.setVisibility(View.GONE);
            return;
        } else {
            reLoadView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            lv_tabdetail_list.setVisibility(View.VISIBLE);
        }
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer();
                handler.postDelayed(runnable, Constants.TIME_RELOADE);
            }
        });
    }

    private boolean isRefresh = false;// 当前是否是下拉刷新
    private boolean isLoadMore = false;// 当前是否是加载更多

    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage < totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                isLoadMore = false;
                lv_tabdetail_list.loadMoreFinished();
                //                Utils.showToast(R.string.no_more);
                Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            }
        }

    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(1);
    }

    private int currentPage = 0;
    private List<HuaTiItem> lists = new ArrayList<>();
    private int totalPages = 0;

    private void loadList(final int page) {
        String url = NetworkConstants.MY_THREAD_ALL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        //        params.put("uid", Global.user.uid);
        //        params.put("uid", "290388");
        GsonRequest<HuaTiListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                HuaTiListDataResponse.class, true, params,
                new Response.Listener<HuaTiListDataResponse>() {
                    @Override
                    public void onResponse(HuaTiListDataResponse response) {
                        if (response.isSuccess()) {
                            handler.removeCallbacks(runnable);
                            loading.setVisibility(View.INVISIBLE);
                            reLoadView.setVisibility(View.GONE);
                            if (response.data.datalist == null) {
                                noListKey = "nolist";
                                wofabiao_text.setText("我发表（" + response.data.thread_create_num + "）");
                                wohuifu_text.setText("我回复（" + response.data.thread_comment_num + "）");
                                adapter = new SpareAdapter();
                                lv_tabdetail_list.setAdapter(adapter);
                            } else {
                                if (page == 1 || page == 0) {
                                    lists.clear();
                                }
                                Log.e("datalist", response.data.datalist.toString());
                                Collections.addAll(lists, response.data.datalist);
                                noListKey = "";
                                currentPage = response.data.cur_page;
                                totalPages = response.data.total_page;
                                wofabiao_text.setText("我发表（" + response.data.thread_create_num + "）");
                                wohuifu_text.setText("我回复（" + response.data.thread_comment_num + "）");
                                parseListJson();
                            }
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(true);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                Utils.showToast(R.string.generic_failure);
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (lists != null && lists.size() > 0) {
                    handler.removeCallbacks(runnable);
                }
                if (isRefresh) {
                    lv_tabdetail_list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    lv_tabdetail_list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson() {
        if (!isLoadMore) {
            adapter = new SpareAdapter();
            lv_tabdetail_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (!TextUtils.isEmpty(noListKey)) {
                return 1;
            } else {
                return lists.size();
            }
        }

        @Override
        public Object getItem(int position) {
            if (!TextUtils.isEmpty(noListKey)) {
                return null;
            } else {
                return lists.get(position);
            }
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HuaTiHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(mContext, R.layout.item_huati_list, null);
                holder = new HuaTiHolder(view, mContext);
                view.setTag(holder);
            }
            holder = (HuaTiHolder) view.getTag();
            if (!TextUtils.isEmpty(noListKey)) {
                holder.setAdapter(adapter);
                holder.bindItem();
            } else {
                HuaTiItem item = lists.get(position);
                holder.setAdapter(adapter);
                holder.bindItem(item, position);//这里用来把获取到的数据传递给holder
            }
            return view;
        }
    }
}
